import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class BotController implements ActionListener {

	BotView myView;
	int error=0;
	public BotController()
	{
		myView=new BotView();
		myView.addActionListener(this);	}
	public String generateLine(String site)
	{
		String line="127.0.0.1 "+site;
		////System.out.println(line);
		return line;
	}
	
	public void appendLine(String line)
	{
		File file= new File("C:\\Windows\\System32\\drivers\\etc\\hosts");
		try {
			FileWriter fw=new FileWriter(file, true);
			BufferedWriter output=new BufferedWriter(fw);
			output.newLine();
			//System.out.println("WRITE THIS"+line);
			output.write(line);
			output.close();
			} catch (IOException e) {
			//System.out.println("Please make sure that you are running this program as an Admin! Right click on program and select 'Run as Administrator'!");
			error=1;
				
		}
	}
	
	public boolean checkFormat(String site)
	{
		Pattern p=Pattern.compile("^(www).*");
		Matcher m=p.matcher(site);
		if(m.find())
		{
			return true;
		}
		else
		{
			return false;				
		}
	}
	


	@Override
	public void actionPerformed(ActionEvent arg0) {
		
		myView.getMessage().setText("");
		if(arg0.getActionCommand()=="OK")
		{
			String input=myView.getSite().getText();
			////System.out.println(input);
			if(checkFormat(input))
			{
				String newLineInHosts=generateLine(input);
				//System.out.println(newLineInHosts);
				appendLine(newLineInHosts);
				if(error==1)
				{
					myView.getMessage().setText("Close program. Right click start.bat, run as admin!");
					myView.getSite().setText("Error, run as admin!");
				}
				else
				{
				//System.out.println("PUSHED");
				myView.getSite().setText("");
				myView.getMessage().setText("Successfully blocked site!");	
			}}
			else
			{
				myView.getMessage().setText("Invalid: Please enter in format www.site.com !");	
			}
		}
		else
		{
			myView.setVisible(false);
			myView.dispose();
		}
	}
	
	
	
	

}
